package com.h3c.ptability.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eos.common.constant.StatusCodeEnum;
import com.eos.common.custom.BusinessException;
import com.eos.common.util.UserUtils;
import com.h3c.ptability.bo.DeptManagerBO;
import com.h3c.ptability.bo.SearchDeptsManagersBO;
import com.h3c.ptability.cache.DeptCache;
import com.h3c.ptability.cache.PtEnumCache;
import com.h3c.ptability.cache.UserCache;
import com.h3c.ptability.client.DataCenterFeignClient;
import com.h3c.ptability.client.EosSyncDataClient;
import com.h3c.ptability.dto.DeptManagerDTO;
import com.h3c.ptability.dto.LoginUserDTO;
import com.h3c.ptability.dto.OptionsDTO;
import com.h3c.ptability.dto.PtDeptDTO;
import com.h3c.ptability.dto.eos.EosSpecialDeptDto;
import com.h3c.ptability.entity.PtAllWorker;
import com.h3c.ptability.entity.PtDept;
import com.h3c.ptability.entity.PtManagementAll;
import com.h3c.ptability.entity.PtUserDept;
import com.h3c.ptability.enums.AutoOpTypeEnum;
import com.h3c.ptability.mapper.PtAllWorkerMapper;
import com.h3c.ptability.mapper.PtDeptMapper;
import com.h3c.ptability.mapstruct.PtDeptMapstruct;
import com.h3c.ptability.mapstruct.PtUserDeptMapstruct;
import com.h3c.ptability.service.CommService;
import com.h3c.ptability.service.EosAuthService;
import com.h3c.ptability.service.IPtDeptService;
import com.h3c.ptability.service.IPtUserDeptService;
import com.h3c.ptability.utils.*;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.connection.stream.StreamInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Copyright (C), 2020-2020, h3c
 * FileName: PtDeptServiceImpl
 *
 * @Author: l22886
 * @Date: 2022-03-14
 * Description: pt_dept serviceImpl
 * Version: 1.0
 */
@Slf4j
@Service
public class PtDeptServiceImpl extends ServiceImpl<PtDeptMapper, PtDept> implements IPtDeptService {

    @Resource
    private PtDeptMapper ptDeptMapper;

    @Resource
    private UserUtils userUtils;

    @Resource
    DeptTree deptTree;

    @Value("${performance.manage.account}")
    private String performanceAccount;
    @Value("${performance.manage.password}")
    private String performancePassword;

    @Value("${performance.account}")
    private String prsAccount;
    @Value("${performance.password}")
    private String prsPassword;

    @Value("${dept.account}")
    private String deptAccount;
    @Value("${dept.manager.account}")
    private String managerAccount;
    @Value("${dept.pwd}")
    private String deptPwd;
    @Value("${dept.manager.pwd}")
    private String managerPwd;

/*    dept.account=eos_inventory
    dept.pwd=123456
    dept.manager.account=eos_prs
    dept.manager.pwd=123456*/

    @Autowired
    private EosSyncDataClient eosSyncDataClient;

    @Autowired
    private IPtUserDeptService ptUserDeptService;

    @Autowired
    private DataCenterFeignClient dataCenterFeignClient;

    @Autowired
    private CommService commService;

    @Autowired
    private EosAuthService eosAuthService;

    @Resource
    private PtAllWorkerMapper ptAllWorkerMapper;

    private static List<PtDept> allDeptCache = new ArrayList<>();

    public final static String redisDept = BusiEnumDefine.REDIS_PREFIX_NAME + "dept-";

    /**
     * @title: selectFuzzyByDto
     * @description: 模糊查询操作
     * @params: [ dto ]
     * @return: java.util.List
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public List<PtDeptDTO> selectFuzzyByDto(PtDeptDTO dto) {
        //List<PtDept> list = ptDeptMapper.selectByExample(initFuzzyExample(dto));
        List<PtDept> list = ptDeptMapper.queryListByFuzzy(JSONObject.parseObject(JSONObject.toJSONString(dto), PtDept.class));
        return JSONArray.parseArray(JSONArray.toJSONString(list), PtDeptDTO.class);
    }

    /**
     * @title: selectByDto
     * @description: 精确查询操作
     * @params: [ dto ]
     * @return: java.util.List
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public List<PtDeptDTO> selectByDto(PtDeptDTO dto) {
        dto.setDeptStatus(1);
        List<PtDept> list = ptDeptMapper.queryList(JSONObject.parseObject(JSONObject.toJSONString(dto), PtDept.class));
        List<PtDeptDTO> dtoList = JSONArray.parseArray(JSONArray.toJSONString(list), PtDeptDTO.class);
        for (PtDeptDTO ptDeptDTO : dtoList) {
            //部门体系名称抓取
            if (Objects.nonNull(ptDeptDTO.getDeptSystem())) {
                ptDeptDTO.setDeptSystemStr(PtEnumCache.getEnumDataInRedis("ptability-manage", "DEPT_SYSTEM", String.valueOf(ptDeptDTO.getDeptSystem())));
            }
        }
        return dtoList;
    }

    /**
     * @title: insertDto
     * @description: 插入操作
     * @params: [ dto ]
     * @return: Integer
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public Integer insertDto(PtDeptDTO dto) {
        //if (null == dto.getId() || "".equals(dto.getId())) {
        //    String pkId = idWorker.nextId() + "";
        //    dto.setId(pkId);
        //}
        return ptDeptMapper.insertPtDept(JSONObject.parseObject(JSON.toJSONString(dto), PtDept.class));
    }

    /**
     * @title: updateDto
     * @description: 修改操作
     * @params: [ dto ]
     * @return: Integer
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public Integer updateDto(PtDeptDTO dto) {
        //if (null != dto && null != dto.getId() && !"".equals(dto.getId())) {
        return ptDeptMapper.updatePtDept(JSONObject.parseObject(JSON.toJSONString(dto), PtDept.class));
        //return ptDeptMapper.updateByPrimaryKey(JSONObject.parseObject(JSON.toJSONString(dto), PtDept.class));
        //} else {
        //    return 0;
        //}
    }

    /**
     * @title: deleteDto
     * @description: 删除操作
     * @params: [ dto ]
     * @return: Integer
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public Integer deleteDto(PtDeptDTO dto) {
        //if (null != dto && null != dto.getId() && !"".equals(dto.getId())) {
        return ptDeptMapper.deletePtDept(JSONObject.parseObject(JSON.toJSONString(dto), PtDept.class));
        //return ptDeptMapper.deleteByPrimaryKey(dto.getId());
        //} else {
        //    return 0;
        //}
    }


    /**
     * @title: initFuzzyExample
     * @description: 初始化 模糊查询 example
     * @params: [ dto ]
     * @return: tk.mybatis.mapper.entity.Example
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    private Example initFuzzyExample(PtDeptDTO dto) {
        Example example = InitExampleOrderByUtils.initExampleOrderBy(PtDept.class, dto.getOrderBy());
        Example.Criteria criteriaName = example.createCriteria();
        if (null != dto) {
            if (null != dto.getDeptId() && !"".equals(dto.getDeptId())) {
                criteriaName.andLike("DeptId", "%" + dto.getDeptId() + "%");
            }
            if (null != dto.getDeptName() && !"".equals(dto.getDeptName())) {
                criteriaName.andLike("DeptName", "%" + dto.getDeptName() + "%");
            }
            if (null != dto.getDeptNameEn() && !"".equals(dto.getDeptNameEn())) {
                criteriaName.andLike("DeptNameEn", "%" + dto.getDeptNameEn() + "%");
            }
            if (null != dto.getShortName() && !"".equals(dto.getShortName())) {
                criteriaName.andLike("ShortName", "%" + dto.getShortName() + "%");
            }
            if (null != dto.getDeptLevel() && !"".equals(dto.getDeptLevel())) {
                criteriaName.andLike("DeptLevel", "%" + dto.getDeptLevel() + "%");
            }
            if (null != dto.getParentId() && !"".equals(dto.getParentId())) {
                criteriaName.andLike("ParentId", "%" + dto.getParentId() + "%");
            }
            if (null != dto.getDeptStatus() && !"".equals(dto.getDeptStatus())) {
                criteriaName.andLike("DeptStatus", "%" + dto.getDeptStatus() + "%");
            }
            if (null != dto.getDeptNameChain() && !"".equals(dto.getDeptNameChain())) {
                criteriaName.andLike("DeptNameChain", "%" + dto.getDeptNameChain() + "%");
            }
            if (null != dto.getDeptCodeChain() && !"".equals(dto.getDeptCodeChain())) {
                criteriaName.andLike("DeptCodeChain", "%" + dto.getDeptCodeChain() + "%");
            }
            if (null != dto.getDeptManagerId() && !"".equals(dto.getDeptManagerId())) {
                criteriaName.andLike("DeptManagerId", "%" + dto.getDeptManagerId() + "%");
            }
            if (null != dto.getDeptManagerName() && !"".equals(dto.getDeptManagerName())) {
                criteriaName.andLike("DeptManagerName", "%" + dto.getDeptManagerName() + "%");
            }
            if (null != dto.getDeptCategory() && !"".equals(dto.getDeptCategory())) {
                criteriaName.andLike("DeptCategory", "%" + dto.getDeptCategory() + "%");
            }
            if (null != dto.getDeptSystem() && !"".equals(dto.getDeptSystem())) {
                criteriaName.andLike("DeptSystem", "%" + dto.getDeptSystem() + "%");
            }
            if (null != dto.getBelongDeptname() && !"".equals(dto.getBelongDeptname())) {
                criteriaName.andLike("BelongDeptname", "%" + dto.getBelongDeptname() + "%");
            }
        }
        return example;
    }

    /**
     * @title: initExample
     * @description: 初始化 精确查询 example
     * @params: [ dto ]
     * @return: tk.mybatis.mapper.entity.Example
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    private Example initExample(PtDeptDTO dto) {
        Example example = InitExampleOrderByUtils.initExampleOrderBy(PtDept.class, dto.getOrderBy());
        Example.Criteria criteriaName = example.createCriteria();
        if (null != dto) {
            if (null != dto.getDeptId() && !"".equals(dto.getDeptId())) {
                criteriaName.andEqualTo("DeptId", dto.getDeptId());
            }
            if (null != dto.getDeptName() && !"".equals(dto.getDeptName())) {
                criteriaName.andEqualTo("DeptName", dto.getDeptName());
            }
            if (null != dto.getDeptNameEn() && !"".equals(dto.getDeptNameEn())) {
                criteriaName.andEqualTo("DeptNameEn", dto.getDeptNameEn());
            }
            if (null != dto.getShortName() && !"".equals(dto.getShortName())) {
                criteriaName.andEqualTo("ShortName", dto.getShortName());
            }
            if (null != dto.getDeptLevel() && !"".equals(dto.getDeptLevel())) {
                criteriaName.andEqualTo("DeptLevel", dto.getDeptLevel());
            }
            if (null != dto.getParentId() && !"".equals(dto.getParentId())) {
                criteriaName.andEqualTo("ParentId", dto.getParentId());
            }
            if (null != dto.getDeptStatus() && !"".equals(dto.getDeptStatus())) {
                criteriaName.andEqualTo("DeptStatus", dto.getDeptStatus());
            }
            if (null != dto.getDeptNameChain() && !"".equals(dto.getDeptNameChain())) {
                criteriaName.andEqualTo("DeptNameChain", dto.getDeptNameChain());
            }
            if (null != dto.getDeptCodeChain() && !"".equals(dto.getDeptCodeChain())) {
                criteriaName.andEqualTo("DeptCodeChain", dto.getDeptCodeChain());
            }
            if (null != dto.getDeptManagerId() && !"".equals(dto.getDeptManagerId())) {
                criteriaName.andEqualTo("DeptManagerId", dto.getDeptManagerId());
            }
            if (null != dto.getDeptManagerName() && !"".equals(dto.getDeptManagerName())) {
                criteriaName.andEqualTo("DeptManagerName", dto.getDeptManagerName());
            }
            if (null != dto.getDeptCategory() && !"".equals(dto.getDeptCategory())) {
                criteriaName.andEqualTo("DeptCategory", dto.getDeptCategory());
            }
            if (null != dto.getDeptSystem() && !"".equals(dto.getDeptSystem())) {
                criteriaName.andEqualTo("DeptSystem", dto.getDeptSystem());
            }
            if (null != dto.getBelongDeptname() && !"".equals(dto.getBelongDeptname())) {
                criteriaName.andEqualTo("BelongDeptname", dto.getBelongDeptname());
            }
        }
        return example;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = "ptDeptList", key = "#p0", allEntries = true)
    public void syncPtDept(Boolean flag) {
        if (flag) {
            //未同步前的数据库中的部门信息
            List<PtDept> ptDeptListEx = ptDeptMapper.queryListByFuzzy(null);
            List<PtDept> ptDeptDOList = getPtDeptListFromEOS(ptDeptListEx);

            //需要更新的部门
            List<PtDept> ptDeptUpdateList = new ArrayList<>();
            //需要插入的部门
            List<PtDept> ptDeptInsertList = new ArrayList<>();

            //先将所有部门状态更为false
            LambdaUpdateWrapper<PtDept> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(PtDept::getDeptStatus, 2);
            update(null, updateWrapper);

            List<Integer> deptIdList = new ArrayList<>();
            ptDeptListEx.forEach(ptDept -> deptIdList.add(ptDept.getDeptId()));
            for (PtDept ptDept : ptDeptDOList) {
                ptDept.setDeptStatus(1);
                if (deptIdList.contains(ptDept.getDeptId())) {
                    ptDeptUpdateList.add(ptDept);
                } else {
                    ptDeptInsertList.add(ptDept);
                }
            }
            if (!CollectionUtils.isEmpty(ptDeptUpdateList)) {
                for (PtDept ptDept : ptDeptUpdateList) {
                    ptDeptMapper.updatePtDept(ptDept);
                }
            }
            if (!CollectionUtils.isEmpty(ptDeptInsertList)) {
                for (PtDept ptDept : ptDeptInsertList) {
                    ptDeptMapper.insert(ptDept);
                }
            }
            syncDeptManagerNew();
            commService.initDeptData();
            //同步主管信息
        } else {
            throw new BusinessException(StatusCodeEnum.UN_AUTH);
        }
    }

    private List<PtDept> getPtDeptListFromEOS(List<PtDept> ptDeptListEx) {
        Map<Integer, List<PtDept>> exMap = ptDeptListEx.stream().distinct().collect(Collectors.groupingBy(PtDept::getDeptId));
        try {
            JSONObject allDept = eosSyncDataClient.queryAllDept("Bearer " + commService.getEosToken());
//            JSONObject allDept = dataCenterFeignClient.queryAllDept("Bearer " + commService.getInventoryToken());
            List deptList = (List) allDept.get("data");
            if (deptList == null) {
                throw new AppBusinessException("" + allDept.get("message"));
            }
            List<PtDept> ptDeptList = new ArrayList<>();
            Map<String, String> needReplaceDeptNameMap = new HashMap<>();

            for (Object dept : deptList) {
                //PtDept PtDeptEx=PtDeptMapper.queryList(new PtDept().setDeptId(Integer.valueOf(((LinkedHashMap) dept).get("dept_code").toString()))).get(0);
                Integer deptId = Integer.valueOf(((LinkedHashMap) dept).get("dept_code").toString());
                PtDept ptDept = new PtDept();
                ptDept.setDeptId(deptId);
                List<PtDept> ptDeptExList = exMap.get(deptId);
                if (ptDeptExList != null && ptDeptExList.size() > 0) {
                    PtDept ptDeptEx = ptDeptExList.get(0);
                    BeanUtils.copyProperties(ptDeptEx, ptDept);
                }
                //////////////////////////////////////测试环境数据有些名字为空，生产环境需要修改
                String deptName = ((LinkedHashMap) dept).get("dept_name") == null ? ((LinkedHashMap) dept).get("dept_code").toString() : ((LinkedHashMap) dept).get("dept_name").toString();
                Integer deptLevel = Integer.valueOf(((LinkedHashMap) dept).get("dept_level").toString());
                //Integer deptCode = Integer.valueOf(((LinkedHashMap) dept).get("dept_code").toString());
                Integer supDeptCode = Integer.valueOf(((LinkedHashMap) dept).get("sup_dept_code").toString());
                String deptNameChain = ((LinkedHashMap) dept).get("dept_name_chain").toString();
                String deptCodeChain = ((LinkedHashMap) dept).get("dept_code_chain").toString();

                if (!StringUtils.isEmpty(deptName)
                        && deptName.indexOf("/") > 0) {
                    String convertDetpName = deptName.replaceAll("/", "&");
                    needReplaceDeptNameMap.put(deptName, convertDetpName);
                    deptName = convertDetpName;
                }
                ptDept.setDeptName(deptName);
                //PtDept.setDeptId(deptCode);
                if (deptLevel == 1 && ((LinkedHashMap) dept).get("deptAbbreviation") != null) {
                    ptDept.setShortName(((LinkedHashMap) dept).get("deptAbbreviation").toString());
                }
                ptDept.setDeptLevel(deptLevel);
                ptDept.setParentId(supDeptCode);
                ptDept.setDeptStatus(1);
                ptDept.setDeptNameChain(((LinkedHashMap) dept).get("dept_name") == null ? deptNameChain + deptName : deptNameChain);
                ptDept.setDeptCodeChain(((LinkedHashMap) dept).get("dept_name") == null ? deptCodeChain + deptName : deptCodeChain);
                ptDeptList.add(ptDept);
            }
            for (PtDept ptDept : ptDeptList) {
                String deptNameChain = ptDept.getDeptNameChain();
                for (String needReplaceDeptName : needReplaceDeptNameMap.keySet()) {
                    if (!StringUtils.isEmpty(deptNameChain)
                            && deptNameChain.indexOf(needReplaceDeptName) > 0) {
                        deptNameChain = deptNameChain.replace(needReplaceDeptName, needReplaceDeptNameMap.get(needReplaceDeptName));
                        ptDept.setDeptNameChain(deptNameChain);
                    }
                }
            }
            return ptDeptList;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    //同步部门主管
    public void syncDeptManager() {
//        Map<String, Object> dataCacheMap = CommService.dataCacheMap;
        String token = userUtils.getToken(prsAccount, prsPassword);
//        commService.getEosToken();
        // String token = userUtils.getToken(eosPrsAccount, eosPrsPassword);
        JSONObject allManager = eosSyncDataClient.queryDeptManage("Bearer " + token);
        List<PtDept> newPtdeptList = new ArrayList<>();
        JSONArray jsonArray = allManager.getJSONArray("data");
        if (jsonArray != null) {
            for (Object jsonObj : jsonArray) {
                JSONObject jsonObject = JSONObject.parseObject(jsonObj.toString());
//                PtDept ptDept = (PtDept) dataCacheMap.get("dept-" + jsonObject.get("dept_code"));
                String newManagerId = (String) jsonObject.get("emp_code");
                if (!StringUtils.isEmpty(newManagerId)) {
                    PtDept ptDept = JSON.parseObject(RedisUtil.get(redisDept + jsonObject.get("dept_code")), PtDept.class);
                    if (!ObjectUtils.isEmpty(ptDept)) {
                        String oldManagerId = ptDept.getDeptManagerId();
                        if (!newManagerId.equals(oldManagerId)) {
                            ptDept.setDeptManagerId(newManagerId);
                            ptDept.setDeptManagerName(jsonObject.get("emp_name") + "/" + newManagerId);
                            newPtdeptList.add(ptDept);
                            ptDeptMapper.updatePtDept(ptDept);
                        }
                    }
                }
            }
        }
    }

    //同步部门主管
    public void syncDeptManagerNew() {
        String token = userUtils.getToken(managerAccount, managerPwd);
//        commService.getEosToken();
        // String token = userUtils.getToken(eosPrsAccount, eosPrsPassword);
        JSONObject allManager = eosSyncDataClient.queryDeptManage("Bearer " + token);
//        List<PtDept> newSddeptList = new ArrayList<>();
        List<PtDept> deptList = new ArrayList<>();
        JSONArray jsonArray = allManager.getJSONArray("data");
        List<DeptManagerDTO> deptManagerDTOS = JSONArray.parseArray(jsonArray.toJSONString(), DeptManagerDTO.class);
        Map<String, List<DeptManagerDTO>> map = deptManagerDTOS.stream().collect(
                Collectors.groupingBy(DeptManagerDTO::getDeptId));
        for (Map.Entry<String, List<DeptManagerDTO>> m : map.entrySet()) {
            PtDept ptDept = new PtDept();
            List<DeptManagerDTO> deptManagerDTOS1 = m.getValue();
            StringBuilder id = new StringBuilder();
            StringBuilder name = new StringBuilder();

            deptManagerDTOS1.forEach(deptManagerDTO1 -> {
                String newManagerId = deptManagerDTO1.getDeptManagerId();
                String newManagerName = deptManagerDTO1.getDeptManagerName();
                if (!StringUtils.isEmpty(newManagerId)) {
                    id.append(newManagerId).append(",");
                    name.append(newManagerName).append("/").append(newManagerId).append(",");
                    int l = id.length() - 1;
                    int n = name.length() - 1;
                    ptDept.setDeptManagerId(id.substring(0, l));
                    ptDept.setDeptManagerName(name.substring(0, n));
                } else {
                    ptDept.setDeptManagerId("");
                    ptDept.setDeptManagerName("");
                }
                ptDept.setDeptId(Integer.parseInt(m.getKey()));
            });
            deptList.add(ptDept);
        }
        deptList.forEach(dept -> {
            PtDept ptDept = JSON.parseObject(RedisUtil.get(redisDept + dept.getDeptId()), PtDept.class);
            if (!ObjectUtils.isEmpty(ptDept)) {
                XxlJobLogger.log(JSONObject.toJSONString(ptDept));
                ptDeptMapper.updatePtDeptManager(dept);
            }
        });
    }

    @Override
    public List<PtDeptDTO> changeRootToChildList(PtDeptDTO root) {
        if (root == null || CollectionUtils.isEmpty(root.getChildren())) {
            return new ArrayList<>();
        }
        return root.getChildren().stream().collect(Collectors.toList());
    }

    @Override
    public PtDeptDTO getAuthorizeChildTree(String appId, String workerId) {
        if (org.apache.commons.lang3.StringUtils.isBlank(appId)) {
            throw new AppBusinessException("appId不能为空");
        }
        if (org.apache.commons.lang3.StringUtils.isBlank(workerId)) {
            throw new AppBusinessException("工号不能为空");
        }
        PtDeptDTO childTree = deptTree.getChildTree(BusiEnumDefine.H3C_CODE);
        if (childTree == null || CollectionUtils.isEmpty(childTree.getChildren())) {
            return null;
        }

        PtAllWorker loginWorker = ptAllWorkerMapper.selectOne(new QueryWrapper<PtAllWorker>().lambda()
                .eq(PtAllWorker::getWorkerId, workerId));

        boolean ssc = isSSCRole(loginWorker.getDomainAccount(), appId);
        if (ssc) {
            reduceParent(childTree);
            //return childTree.getChildren().stream().collect(Collectors.toList());
            return childTree;
        }

        LambdaQueryWrapper<PtUserDept> userDeptQuery = new QueryWrapper<PtUserDept>()
                .lambda()
                .eq(PtUserDept::getAppId, appId)
                .like(PtUserDept::getUserIds, workerId);
        Map<Integer, PtUserDept> allAuthorizeDeptMap = ptUserDeptService.list(userDeptQuery).stream().collect(
                Collectors.toMap(PtUserDept::getDeptId, dept -> dept));
        judgeAuthorizeDeptNoTree(childTree, workerId, allAuthorizeDeptMap);

        reduceUnAuthorizedParent(childTree);
        //return childTree.getChildren().stream().collect(Collectors.toList());
        return childTree;
    }

    public void reduceUnAuthorizedParent(PtDeptDTO childTree) {
        if (!CollectionUtils.isEmpty(childTree.getChildren())) {
            List<PtDeptDTO> childList = childTree.getChildren().stream().filter(dept -> dept.getHasAuthorize() != null && dept.getHasAuthorize()).peek(dept -> dept.setParent(null)).collect(Collectors.toList());
            childTree.setChildren(childList);
            for (PtDeptDTO ptDeptDTO : childList) {
                reduceUnAuthorizedParent(ptDeptDTO);
            }
        }
    }

    public void reduceParent(PtDeptDTO childTree) {
        if (!CollectionUtils.isEmpty(childTree.getChildren())) {
            List<PtDeptDTO> childList = childTree.getChildren().stream().peek(dept -> dept.setParent(null)).collect(Collectors.toList());
            childTree.setChildren(childList);
            for (PtDeptDTO ptDeptDTO : childList) {
                reduceParent(ptDeptDTO);
            }
        }
    }


    public boolean isSSCRole(String account, String appId) {
        List<String> roles = eosAuthService.getUserRoleByAccount(account, appId);
        for (String role : roles) {
            if (role.equals("SSC-SIGN")) {
                return true;
            }
        }
        return false;
    }

    public void getAuthorizedCodeAndName(PtDeptDTO root, Map<Integer, PtUserDept> allAuthorizeDeptMap, List<PtDeptDTO> list, boolean isSSC) {
        if (root == null) {
            return;
        }
        if (allAuthorizeDeptMap.get(root.getDeptId()) != null) {
            String userNames = allAuthorizeDeptMap.get(root.getDeptId()).getUserNames();
            String userIds = allAuthorizeDeptMap.get(root.getDeptId()).getUserIds();
            PtDeptDTO dto = new PtDeptDTO();
            dto.setDeptId(root.getDeptId());
            dto.setDeptName(root.getDeptName());
            dto.setDeptLevel(root.getDeptLevel());
            dto.setDeptNameChain(root.getDeptNameChain());
            dto.setUserNames(userNames.substring(0, userNames.length() - 1));
            dto.setUserIds(userIds.substring(0, userIds.length() - 1));
            list.add(dto);
        } else if (isSSC) {
            PtDeptDTO dto = new PtDeptDTO();
            dto.setDeptId(root.getDeptId());
            dto.setDeptName(root.getDeptName());
            dto.setDeptLevel(root.getDeptLevel());
            dto.setDeptNameChain(root.getDeptNameChain());
            list.add(dto);
        }
        if (!CollectionUtils.isEmpty(root.getChildren())) {
            for (PtDeptDTO child : root.getChildren()) {
                getAuthorizedCodeAndName(child, allAuthorizeDeptMap, list, isSSC);
            }
        }
    }

    @Override
    public List<PtDeptDTO> getAuthorizeDeptTree(PtDeptDTO ptDeptDTO, String domain) {
        if (org.apache.commons.lang3.StringUtils.isBlank(ptDeptDTO.getAppId())) {
            throw new AppBusinessException("appId不能为空");
        }
        if (ptDeptDTO.getDeptId() == null) {
            throw new AppBusinessException("部门id不能为空");
        }
        PtAllWorker loginWorker = ptAllWorkerMapper.selectOne(new QueryWrapper<PtAllWorker>().lambda()
                .eq(PtAllWorker::getDomainAccount, domain));

        PtDeptDTO childTree = deptTree.getChildTree(ptDeptDTO.getDeptId());
        if (childTree == null || CollectionUtils.isEmpty(childTree.getChildren())) {
            return new ArrayList<>();
        }
        boolean ssc = isSSCRole(domain, ptDeptDTO.getAppId());
        if (ssc) {

            setAuthorizedUsersForSSC(childTree, ptDeptDTO.getAppId());
            return childTree.getChildren().stream().peek(child -> {
                child.setChildren(null);
                child.setParent(null);
                child.setHasAuthorize(true);
                child.setCanAuthorize(true);
            }).collect(Collectors.toList());
        }

        LambdaQueryWrapper<PtUserDept> userDeptQuery = new QueryWrapper<PtUserDept>()
                .lambda()
                .eq(PtUserDept::getAppId, ptDeptDTO.getAppId())
                .like(PtUserDept::getUserIds, loginWorker.getWorkerId());

        Map<Integer, PtUserDept> allAuthorizeDeptMap = ptUserDeptService.list(userDeptQuery).stream().collect(
                Collectors.toMap(PtUserDept::getDeptId, dept -> dept));
        judgeAuthorizeDeptNoTree(childTree, loginWorker.getWorkerId(), allAuthorizeDeptMap);

        return childTree.getChildren().stream().filter(dept -> dept.getHasAuthorize() != null && dept.getHasAuthorize()).peek(dept -> {
            dept.setChildren(null);
            dept.setParent(null);
            dept.setDeptSystemStr(PtEnumCache.getEnumDataInRedis("ptability-manage", "DEPT_SYSTEM", String.valueOf(dept.getDeptSystem())));
        }).collect(Collectors.toList());
    }

    public void setAuthorizedUsersForSSC(PtDeptDTO root, String appId) {
        LambdaQueryWrapper<PtUserDept> userDeptQuery = new QueryWrapper<PtUserDept>()
                .lambda()
                .eq(PtUserDept::getAppId, appId);

        Map<Integer, PtUserDept> allAuthorizeDeptMap = ptUserDeptService.list(userDeptQuery).stream().collect(
                Collectors.toMap(PtUserDept::getDeptId, dept -> dept));
        for (PtDeptDTO child : root.getChildren()) {
            child.setDeptSystemStr(PtEnumCache.getEnumDataInRedis("ptability-manage", "DEPT_SYSTEM", String.valueOf(child.getDeptSystem())));
            if (allAuthorizeDeptMap.containsKey(child.getDeptId())) {
                String userNames = allAuthorizeDeptMap.get(child.getDeptId()).getUserNames();
                String userIds = allAuthorizeDeptMap.get(child.getDeptId()).getUserIds();
                child.setUserNames(userNames.substring(0, userNames.length() - 1));
                child.setUserIds(userIds.substring(0, userIds.length() - 1));
            }
        }
    }

    public void judgeAuthorizeDeptNoTree(PtDeptDTO root, String empCode, Map<Integer, PtUserDept> allAuthorizeDeptMap) {
        if (!CollectionUtils.isEmpty(root.getChildren())) {
            for (PtDeptDTO child : root.getChildren()) {
                judgeAuthorizeDeptNoTree(child, empCode, allAuthorizeDeptMap);
            }
        }

        boolean parentHasAuthorize = false;
        //root.setHasChildren(false);
        if (allAuthorizeDeptMap.keySet().contains(root.getDeptId())) {
            String userNames = allAuthorizeDeptMap.get(root.getDeptId()).getUserNames();
            String userIds = allAuthorizeDeptMap.get(root.getDeptId()).getUserIds();
            root.setUserNames(userNames.substring(0, userNames.length() - 1));
            root.setUserIds(userIds.substring(0, userIds.length() - 1));
            root.setHasAuthorize(true);
            root.setCanAuthorize(true);
            parentHasAuthorize = true;
        }

        allAuthorizeDeptNoTree(root, parentHasAuthorize, allAuthorizeDeptMap);
    }

    public void allAuthorizeDeptNoTree(PtDeptDTO root, boolean parentHasAuthorize, Map<Integer, PtUserDept> allAuthorizeDeptMap) {
        if (root.getParent() != null) {
            root = root.getParent();
            if (root.getHasAuthorize() != null && root.getHasAuthorize()) {
                root.setCanAuthorize(allAuthorizeDeptMap.keySet().contains(root.getDeptId()));
                allAuthorizeDeptNoTree(root, true, allAuthorizeDeptMap);
            } else {
                if (parentHasAuthorize) {
                    root.setHasAuthorize(true);
                } else {
                    if (allAuthorizeDeptMap.keySet().contains(root.getDeptId())) {
                        String userNames = allAuthorizeDeptMap.get(root.getDeptId()).getUserNames();
                        String userIds = allAuthorizeDeptMap.get(root.getDeptId()).getUserIds();
                        root.setUserNames(userNames.substring(0, userIds.length() - 1));
                        root.setUserIds(userIds.substring(0, userIds.length() - 1));
                        root.setHasAuthorize(true);
                        parentHasAuthorize = true;
                    }
                }
                root.setCanAuthorize(allAuthorizeDeptMap.keySet().contains(root.getDeptId()));
                allAuthorizeDeptNoTree(root, parentHasAuthorize, allAuthorizeDeptMap);
            }
        }
    }

    @Override
    public List<PtDeptDTO> getAllAuthorizedDeptList(String appId, String domain) {
        List<PtDeptDTO> result = new ArrayList<>();
        boolean sscRole = isSSCRole(domain, appId);
        String userId = UserCache.getLoginUserByAccountId(domain).getUserId();
        PtDeptDTO root = getAuthorizeChildTree(appId, userId);
        if (root == null) {
            return result;
        }
        Map<Integer, PtUserDept> allAuthorizeDeptMap;
        LambdaQueryWrapper<PtUserDept> userDeptQuery = new QueryWrapper<PtUserDept>()
                .lambda()
                .eq(PtUserDept::getAppId, appId)
                .like(!sscRole, PtUserDept::getUserIds, userId);
        allAuthorizeDeptMap = ptUserDeptService.list(userDeptQuery).stream().collect(
                Collectors.toMap(PtUserDept::getDeptId, dept -> dept));
//        if (sscRole){
//            LambdaQueryWrapper<PtUserDept> userDeptQuery = new QueryWrapper<PtUserDept>()
//                    .lambda()
//                    .eq(PtUserDept::getAppId, appId);
//            allAuthorizeDeptMap = ptUserDeptService.list(userDeptQuery).stream().collect(
//                    Collectors.toMap(PtUserDept::getDeptId, dept -> dept));
//        } else {
//            LambdaQueryWrapper<PtUserDept> userDeptQuery = new QueryWrapper<PtUserDept>()
//                    .lambda()
//                    .eq(PtUserDept::getAppId, appId)
//                    .like(PtUserDept::getUserIds, userId);
//            allAuthorizeDeptMap = ptUserDeptService.list(userDeptQuery).stream().collect(
//                    Collectors.toMap(PtUserDept::getDeptId, dept -> dept));
//        }
        getAuthorizedCodeAndName(root, allAuthorizeDeptMap, result, sscRole);
        return result;
    }

    //查询所有子部门
    @Override
    public List<PtDeptDTO> qyeryChidrenDeptList(PtDeptDTO ptDeptDTO) {
        if (org.apache.commons.lang3.StringUtils.isBlank(ptDeptDTO.getAppId())) {
            throw new AppBusinessException("appId不能为空");
        }
/*        PtDept ptDept = new PtDept();
        ptDept.setParentId(ptDeptDTO.getDeptId());
        ptDept.setDeptStatus(1);
        List<PtDept> ptDeptList = ptDeptMapper.queryList(ptDept);*/
        LambdaQueryWrapper<PtDept> queryWrapper = new QueryWrapper<PtDept>().lambda();
        if (Objects.nonNull(ptDeptDTO.getDeptId())) {
            queryWrapper.eq(PtDept::getParentId, ptDeptDTO.getDeptId());
        }
        List<PtDept> ptDeptList = ptDeptMapper.selectList(queryWrapper
                .eq(PtDept::getDeptStatus, 1)
        );
        List<PtDeptDTO> ptDeptDTOS = new ArrayList<>();
        for (PtDept dept : ptDeptList) {
            PtDeptDTO ptDeptDTO1 = new PtDeptDTO();
            BeanUtils.copyProperties(dept, ptDeptDTO1);
            if (Objects.nonNull(ptDeptDTO1.getDeptSystem())) {
                ptDeptDTO1.setDeptSystemStr(PtEnumCache.getEnumDataInRedis("ptability-manage", "DEPT_SYSTEM", String.valueOf(dept.getDeptSystem())));
            }
            PtUserDept ptUserDept = ptUserDeptService.getOne(new QueryWrapper<PtUserDept>().lambda()
                    .eq(PtUserDept::getAppId, ptDeptDTO.getAppId())
                    .eq(PtUserDept::getDeptId, dept.getDeptId())
            );
            if (Objects.nonNull(ptUserDept)) {
                if (StringUtils.hasText(ptUserDept.getUserIds())) {
                    ptDeptDTO1.setUserIds(ptUserDept.getUserIds().substring(0, ptUserDept.getUserIds().length() - 1));
                }
                if (StringUtils.hasText(ptUserDept.getUserNames())) {
                    ptDeptDTO1.setUserNames(ptUserDept.getUserNames().substring(0, ptUserDept.getUserNames().length() - 1));
                }
            }
            PtDept ptDept1 = new PtDept();
            ptDept1.setParentId(dept.getDeptId());
            if (ptDeptMapper.queryList(ptDept1).size() > 0) {
                ptDeptDTO1.setHasChildren(true);
            } else {
                ptDeptDTO1.setHasChildren(false);
            }
            ptDeptDTOS.add(ptDeptDTO1);
        }
        return ptDeptDTOS;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setDeptUserRole(PtDeptDTO ptDeptDTO, String domain) {
        //所有需要设置的部门
        LoginUserDTO operator = null;
        boolean needAuthorized = false;
        if (StringUtils.hasText(domain)) {
            operator = UserCache.getLoginUserByAccountId(domain);
            // 只能给自己有权限的部门进行授权
            if (isSSCRole(domain, ptDeptDTO.getAppId())) {
                needAuthorized = false;
            } else {
                PtUserDept root = ptUserDeptService.getOne(new QueryWrapper<PtUserDept>().lambda()
                        .eq(PtUserDept::getDeptId, ptDeptDTO.getDeptId())
                        .eq(PtUserDept::getAppId, ptDeptDTO.getAppId())
                );
                if (root == null || !root.getUserIds().contains(operator.getUserId())) {
                    throw new AppBusinessException("抱歉，您无权限授权该部门");
                }
                needAuthorized = true;
            }
        }
        List<PtDept> sdDeptListAll = new ArrayList<>();
        PtDept sdDept = new PtDept();
        sdDept.setDeptId(ptDeptDTO.getDeptId());
        PtDept operatePtDept = ptDeptMapper.queryList(sdDept).get(0);
        //只设置当前部门
        if (ptDeptDTO.getDeptSetMode().equals(1)) {
            sdDeptListAll.add(operatePtDept);
        } else if (ptDeptDTO.getDeptSetMode().equals(2)) {
            PtDept sdDept1 = new PtDept();
            sdDept1.setDeptCodeChain(ptDeptDTO.getDeptId().toString());
            sdDeptListAll = ptDeptMapper.queryListByFuzzy(sdDept1);
        }
        //循环处理所有需要设置的部门
        for (PtDept ptDeptNeedSet : sdDeptListAll) {
            //覆盖原有人员
            if (needAuthorized) {
                PtUserDept root = ptUserDeptService.getOne(new QueryWrapper<PtUserDept>().lambda()
                        .eq(PtUserDept::getDeptId, ptDeptNeedSet.getDeptId())
                        .eq(PtUserDept::getAppId, ptDeptDTO.getAppId())
                );
                if (root == null || !root.getUserIds().contains(operator.getUserId())) {
                    continue;
                }
            }
            if (ptDeptDTO.getPersonSetMode().equals(1)) {
                ptUserDeptService.remove(new QueryWrapper<PtUserDept>().lambda()
                        .eq(PtUserDept::getDeptId, ptDeptNeedSet.getDeptId())
                        .eq(PtUserDept::getAppId, ptDeptDTO.getAppId())
                );
                if (StringUtils.hasText(ptDeptDTO.getUsers())) {
                    StringBuilder userNames = new StringBuilder();
                    for (String s : ptDeptDTO.getUsers().split(",")) {
                        userNames.append(UserCache.getLoginUserByUserId(s).getWorkerName())
                                .append("/")
                                .append(s)
                                .append(",");
                    }
                    ptUserDeptService.save(new PtUserDept()
                            .setAppId(ptDeptDTO.getAppId())
                            .setDeptId(ptDeptNeedSet.getDeptId())
                            .setAppId(ptDeptDTO.getAppId())
                            .setOperateTime(new Date())
                            .setOperatorId(UserCache.getLoginUserNameAndId())
                            .setUserIds(ptDeptDTO.getUsers().concat(","))
                            .setUserNames(userNames.toString())
                    );
                }
            } else if (ptDeptDTO.getPersonSetMode().equals(2)) {
                //原有人员追加
                PtUserDept oldUserDept = ptUserDeptService.getOne(new QueryWrapper<PtUserDept>().lambda()
                        .eq(PtUserDept::getDeptId, ptDeptNeedSet.getDeptId())
                        .eq(PtUserDept::getAppId, ptDeptDTO.getAppId())
                );
                if (Objects.isNull(oldUserDept)) {
                    oldUserDept = new PtUserDept();
                    oldUserDept.setAppId(ptDeptDTO.getAppId())
                            .setDeptId(ptDeptNeedSet.getDeptId())
                            .setUserIds("")
                            .setUserNames("")
                            .setOperateTime(new Date())
                            .setOperatorId(UserCache.getLoginUserNameAndId());
                    ptUserDeptService.save(oldUserDept);
                }
                String userIds = oldUserDept.getUserIds();
                String userNames = oldUserDept.getUserNames();
                for (String userId : ptDeptDTO.getUsers().split(",")) {
                    if (userIds.contains(userId)) {
                        continue;
                    }
                    userIds = userIds.concat(userId).concat(",");
                    userNames = userNames.concat(UserCache.getLoginUserByUserId(userId).getWorkerName())
                            .concat("/")
                            .concat(userId)
                            .concat(",");
                }
                ptUserDeptService.update(null, new LambdaUpdateWrapper<PtUserDept>()
                        .set(PtUserDept::getUserIds, userIds)
                        .set(PtUserDept::getUserNames, userNames)
                        .set(PtUserDept::getOperateTime, new Date())
                        .set(PtUserDept::getOperatorId, UserCache.getLoginUserNameAndId())
                        .eq(PtUserDept::getDeptId, ptDeptNeedSet.getDeptId())
                        .eq(PtUserDept::getAppId, ptDeptDTO.getAppId())
                );
            }
        }
        MqUtils.recordAuthChangeLog("sd_dept", AutoOpTypeEnum.UPDATE, JSONObject.toJSONString(ptDeptDTO), "通过界面操作设置部门相关人员");
        return;
    }

    @Override
    public void importDeptSetList(String appId, MultipartFile file) {
        String fileContent = commService.parseExcelByTemplate("PT_DEPT_IMPORT", file);
        List<PtDeptDTO> deptDTOS = JSONUtil.toList(JSONUtil.parseArray(fileContent), PtDeptDTO.class);
        List<PtDeptDTO> ptDeptDTOS = deptDTOS.stream().filter(s -> StringUtils.hasText(s.getUserIds()) && !s.getDeptId().equals("50040000")).collect(Collectors.toList());
        List<PtUserDept> ptUserDepts = PtUserDeptMapstruct.INSTANCE.dtoToEntity(ptDeptDTOS);
        ptUserDepts.stream().forEach(s -> s.setOperateTime(new Date())
                .setOperatorId(UserCache.getLoginUserNameAndId())
                .setAppId(appId)
        );
        for (PtUserDept ptUserDept : ptUserDepts) {
            LambdaUpdateWrapper<PtUserDept> updateWrapper = new LambdaUpdateWrapper<>();
            if (ptUserDept.getUserIds().equals("无")) {
                updateWrapper.set(PtUserDept::getUserIds, null);
            }
            StringBuilder userNames = new StringBuilder();
            for (String s : ptUserDept.getUserIds().split(",")) {
                userNames.append(UserCache.getLoginUserByUserId(s).getWorkerName())
                        .append("/")
                        .append(s)
                        .append(",");
            }
            ptUserDept.setUserNames(userNames.toString());
            boolean success = ptUserDeptService.update(null, updateWrapper
                    .set(PtUserDept::getUserIds, ptUserDept.getUserIds().concat(","))
                    .set(PtUserDept::getUserNames, ptUserDept.getUserNames())
                    .set(PtUserDept::getOperateTime, ptUserDept.getOperateTime())
                    .set(PtUserDept::getOperatorId, ptUserDept.getOperatorId())
                    .eq(PtUserDept::getDeptId, ptUserDept.getDeptId())
                    .eq(PtUserDept::getAppId, appId)
            );
            if (!success) {
                ptUserDeptService.save(ptUserDept);
            }
        }
    }

    @Override
    public void importDeptSystemSet(MultipartFile file) {
        String fileContent = commService.parseExcelByTemplate("PT_DEPT_SYSTEM_IMPORT", file);
        List<PtDeptDTO> deptDTOS = JSONUtil.toList(JSONUtil.parseArray(fileContent), PtDeptDTO.class);
        List<PtDeptDTO> ptDeptDTOS = deptDTOS.stream().filter(s -> !s.getDeptId().equals("50040000")).collect(Collectors.toList());
        List<PtDept> ptDepts = PtDeptMapstruct.INSTANCE.dtoList2entityList(ptDeptDTOS);
        for (PtDept ptDept : ptDepts) {
            LambdaUpdateWrapper<PtDept> updateWrapper = new LambdaUpdateWrapper<>();

            updateWrapper.set(PtDept::getDeptSystem, ptDept.getDeptSystem());
            update(null, updateWrapper
                    .eq(PtDept::getDeptId, ptDept.getDeptId())
            );
        }
    }

    @Override
    public List<OptionsDTO> queryDeptTreeSelection(String deptIds) {
        List<String> deptIdList;
        if (StringUtils.isEmpty(deptIds)) {
            deptIdList = new ArrayList<>();
        } else {
            deptIdList = Arrays.asList(deptIds.split(","));
        }
        List<PtDept> sdDepts = ptDeptMapper.selectList(null);
        List<OptionsDTO> optionList = new ArrayList<>();
        sdDepts.stream().filter(s -> !s.getDeptLevel().equals(0)).filter(s -> s.getDeptStatus() == 1)
                .forEach(o -> optionList.add(new OptionsDTO(String.valueOf(o.getDeptId()),
                        o.getDeptName(), String.valueOf(o.getParentId()), getDeptNameChainNoH3c(o.getDeptNameChain()), o.getDeptLevel())));

        Map<String, List<OptionsDTO>> children = optionList.stream()
                .filter(o -> !"50040000".equals(o.getKey()))
                .collect(Collectors.groupingBy(OptionsDTO::getKey,
                        Collectors.collectingAndThen(Collectors.toList(), list -> list)));
        List<OptionsDTO> parent = optionList.stream().filter(o -> "50040000".equals(o.getKey()))
                .filter(o -> chooseDept1(o.getValue(), deptIdList)).collect(Collectors.toList());

        doChildren(parent, children);

        return parent;
    }

    @Override
    public List<DeptManagerBO> getDeptsManagers(SearchDeptsManagersBO searchDeptsManagersBO) {
        ArrayList<DeptManagerBO> result = new ArrayList<>();
        for (String deptId : searchDeptsManagersBO.getDeptIds()) {
            DeptManagerBO deptManagerBO = new DeptManagerBO();
            List<String> deptManagerList = new ArrayList<>();
            PtDept ptDept = DeptCache.getPtDeptByDeptId(Integer.parseInt(deptId));
            String userIds = ptUserDeptService.getOne(new QueryWrapper<PtUserDept>().lambda()
                    .eq(PtUserDept::getAppId, searchDeptsManagersBO.getAppId())
                    .eq(PtUserDept::getDeptId, deptId)
            ).getUserIds();
            if (StringUtils.hasText(userIds)) {
                PtDept dept = DeptCache.getPtDeptByDeptId(Integer.valueOf(deptId));
                if (Objects.isNull(dept)) {
                    throw new AppBusinessException("部门id:" + deptId + "不存在");
                }
                List<String> userIdList = StrUtil.splitTrim(userIds, ",");
                for (String userId : userIdList) {
                    PtAllWorker ptAllWorker = UserCache.getLoginUserByUserId(userId);
                    List<String> roleByAccount = eosAuthService.getUserRoleByAccount(ptAllWorker.getDomainAccount(), searchDeptsManagersBO.getAppId());
                    if ((searchDeptsManagersBO.getAppId().equals("hr-sign") || searchDeptsManagersBO.getAppId().equals("hr-sign-test")) && ptDept.getDeptCodeChain().contains("50040035")) {
                        if ((dept.getDeptLevel().equals(3) && roleByAccount.contains("deptThreeLeader")) ||
                                (dept.getDeptLevel().equals(2) && roleByAccount.contains("deptTwoLeader")) ||
                                (dept.getDeptLevel().equals(1) && roleByAccount.contains("deptOneLeader"))
                        ) {
                            deptManagerList.add(userId);
                        }
                    } else {
                        if (((dept.getDeptLevel().equals(3) && roleByAccount.contains("deptThreeLeader")) ||
                                (dept.getDeptLevel().equals(2) && roleByAccount.contains("deptTwoLeader")) ||
                                (dept.getDeptLevel().equals(1) && roleByAccount.contains("deptOneLeader")))
                        ) {
                            if (searchDeptsManagersBO.getAppId().equals("hr-sign") || searchDeptsManagersBO.getAppId().equals("hr-sign-test")) {
                                if (!roleByAccount.contains("GBBZ")) {
                                    deptManagerList.add(userId);
                                }
                            } else {
                                deptManagerList.add(userId);
                            }
                        }
                    }
                }
                if (deptManagerList.size() == 0) {
                    deptManagerList = getDeptMangers(deptId);
                }
            } else {
                deptManagerList = getDeptMangers(deptId);
            }
            if (Objects.isNull(deptManagerList) || deptManagerList.size() == 0) {
                continue;
            }
            StringBuilder workerId = new StringBuilder();
            StringBuilder workerName = new StringBuilder();
            StringBuilder domainAccount = new StringBuilder();
            for (String s : deptManagerList) {
                PtAllWorker ptAllWorker = UserCache.getLoginUserByUserId(s);
                workerId.append(ptAllWorker.getWorkerId()).append(",");
                workerName.append(ptAllWorker.getWorkerName()).append(",");
                domainAccount.append(ptAllWorker.getDomainAccount()).append(",");
            }
            deptManagerBO.setDeptId(deptId);
            deptManagerBO.setWorkerId(workerId.deleteCharAt(workerId.length() - 1).toString());
            deptManagerBO.setWorkerName(workerName.deleteCharAt(workerName.length() - 1).toString());
            deptManagerBO.setDomainAccount(domainAccount.deleteCharAt(domainAccount.length() - 1).toString());
            result.add(deptManagerBO);
        }
        return result;
    }

    private List<String> getDeptMangers(String deptId) {
        PtDept dept = DeptCache.getPtDeptByDeptId(Integer.valueOf(deptId));
        if (Objects.isNull(dept)) {
            throw new AppBusinessException("部门id:" + deptId + "不存在");
        }
        String deptManagerId = dept.getDeptManagerId();
        if (org.apache.commons.lang3.StringUtils.isBlank(deptManagerId)) {
            throw new AppBusinessException("部门id:" + deptId + "无部门主管也没有授权用户");
        }
        return StrUtil.splitTrim(deptManagerId, ",");
    }

    /**
     * 获取没有新华三头部的nameChain
     *
     * @param deptNameChain 部门表的nameChain
     * @return
     */
    public static String getDeptNameChainNoH3c(String deptNameChain) {
        if (deptNameChain.contains("/")) {
            int i = deptNameChain.indexOf("/");
            return deptNameChain.substring(i + 1);
        } else {
            return deptNameChain;
        }
    }

    private boolean chooseDept1(String dept1Id, List<String> deptIdList) {
        if (deptIdList.isEmpty()) {
            return true;
        }
        return deptIdList.contains(dept1Id);
    }

    /**
     * 更新本地部门缓存
     */
    private void updateAllDeptCache() {
        allDeptCache = ptDeptMapper.selectList(null);
    }

    private void doChildren(List<OptionsDTO> parent, Map<String, List<OptionsDTO>> children) {
        if (parent == null || parent.isEmpty()) {
            return;
        }
        parent.forEach(p -> {
            List<OptionsDTO> dtos = children.get(p.getValue());
            p.setChildren(dtos);
            doChildren(dtos, children);
        });
    }

    /**
     * 获取特殊部门集合
     *
     * @return 特殊部门集合
     */
    @Override
    public List<EosSpecialDeptDto> getSpecialDeptCodesFromEos() {
        JSONObject allDept = eosSyncDataClient.getSpecialDeptCodesFromEos("Bearer " + commService.getEosToken());
        JSONArray deptJSONArray = allDept.getJSONArray("data");
        List<EosSpecialDeptDto> ptDeptList = deptJSONArray.toJavaList(EosSpecialDeptDto.class);
        if (CollectionUtils.isEmpty(ptDeptList)) {
            throw new AppBusinessException("" + allDept.get("message"));
        }
        //特殊部门处理
        for (EosSpecialDeptDto dept : ptDeptList) {
            if (StringUtils.hasText(dept.getDeptCodes())) {
                dept.setDeptCodeList(Arrays.asList(dept.getDeptCodes().split(",")));
            }
            dept.setDeptCodes(null);
        }
        return ptDeptList;
    }

}
